package cool.taomu.toolkit.jooq

import com.google.inject.Inject
import cool.taomu.toolkit.jooq.provider.JooqContextProvider
import org.aopalliance.intercept.MethodInterceptor
import org.aopalliance.intercept.MethodInvocation
import org.jooq.DSLContext
import org.slf4j.LoggerFactory
import cool.taomu.toolkit.annotations.datasource.Ds

class DataSourceSwitcher implements MethodInterceptor {

    val static LOG = LoggerFactory.getLogger(DataSourceSwitcher);

    @Inject
    JooqContextProvider jooqContextProvider;

    override Object invoke(MethodInvocation invocation) throws Throwable {
        LOG.info("执行方法 {}", invocation.method.name)
        var annotation = invocation.getMethod().getAnnotation(Ds);
        if (annotation !== null) {
            var DSLContext context = jooqContextProvider.use(annotation.value())
            ThreadLocalDSLContext.set(context);
            try {
                return invocation.proceed();
            } finally {
                ThreadLocalDSLContext.clear();
            }
        } else {
            return invocation.proceed();
        }
    }
}
